package com.simple.ds.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.google.common.primitives.Longs;
import com.simple.common.entity.po.ChannelMerchantEntity;
import com.simple.common.entity.po.MerchantEntity;
import com.simple.common.entity.po.TradeEntity;
import com.simple.common.entity.po.sys.ExampleChannel;
import com.simple.common.entity.po.sys.Product;
import com.simple.common.entity.po.sys.Trade;
import com.simple.ds.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yasud
 * @date 2021年09月19日 13:22
 * @description
 */
@Service
public class ExampleChannelApiImpl implements ExampleChannelApi {

    @Autowired
    TradeService tradeService;

    @Autowired
    ProductService productService;

    @Autowired
    MerchantService merchantService;

    @Autowired
    ChannelMerchantService channelMerchantService;


    @Override
    public ExampleChannel findById_(Long id) {
        return null;
    }

    @Override
    public ExampleChannel build(Trade trade) {
        TradeEntity tradeEntity = tradeService.getById(trade.getId());
        Product product = productService.buildProduct(tradeEntity.getApiCode());
        MerchantEntity merchantEntity = merchantService.getById(tradeEntity.getMerchantCode());
        ChannelMerchantEntity channelMerchantEntity = channelMerchantService.findByMerchantCodeAndApiCode(merchantEntity.getMerchantCode(), product.getProductCode());
        return createExampleChannel(merchantEntity, channelMerchantEntity, product);
    }

    private ExampleChannel createExampleChannel(MerchantEntity merchantEntity,
                                                ChannelMerchantEntity channelMerchantEntity,
                                                Product product) {
        ExampleChannel exampleChannel = new ExampleChannel();
        exampleChannel.setId(channelMerchantEntity.getId());
        exampleChannel.setChannelId(channelMerchantEntity.getId());
        exampleChannel.setChannelMerchantId(channelMerchantEntity.getId() + 1);
        exampleChannel.setApplicationId(Longs.fromByteArray(DigestUtil.sha256(merchantEntity.getMerchantCode() + "_application")));
        exampleChannel.setProductId(product.getId());
        exampleChannel.setExampleId(Longs.fromByteArray(DigestUtil.sha256(merchantEntity.getMerchantCode() + "_example")));
        exampleChannel.setEnable(true);
        return exampleChannel;
    }
}
